import {history, post, message, get} from '@/utils/utils'

const managementDetail = {
  namespaced: true,
  state: {
    detail: {},
    list: [],
    pageNum: 1,
    hasData: true
  },

  mutations: {
    save(state, { field, payload }) {
      if (Object.prototype.toString.call(payload) === '[object Object]') {
        state[field] = { ...state[field], ...payload }
      } else {
        state[field] = payload
      }
    }
  },

  actions: {
    getDetail({ commit }, {no, type}) {
      const apiEnum = {
        'merchant': '/mec/merchant/getMerchantInfo',
        'agent': `/agt/agentinfo/getLowerAgentInfo?agentNo=${no}`
      }

      get({api: apiEnum[type],
        data: {mno: no},
        success: ({data}) => {
          commit('save', {field: 'detail', payload: data})
        }})
    },

    getTradeList({ commit, state }, {no, type, pageNum = 1}) {
      const apiEnum = {
        'merchant': '/agt/agenttransactioncumulative/getMecTurnoverByMno',
        'agent': '/mec/merchanttransactioncumulative/getAgentTurnoverByAgentNo'
      }

      get({api: apiEnum[type],
        data: {mno: no, agentNo: no, current: pageNum, size: 10},
        success: ({data}) => {
          data = data || {}

          const {pages, records} = data
          const {list} = state
          let recordList = list

          if (pageNum > 1) {
            recordList = recordList.concat(records)
          } else {
            recordList = records || []
            commit('save', {field: 'hasData', payload: true})
          }

          if (pages === pageNum || pages === 0 || !pages) commit('save', {field: 'hasData', payload: false})

          commit('save', {field: 'pageNum', payload: pageNum})
          commit('save', {field: 'list', payload: recordList})
        }})
    }

  }
}

export default managementDetail
